/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.garagesale.user.web.action;

import com.garagesale.data.DBAccess;
import com.garagesale.data.ShoppingCart;
import com.garagesale.data.User;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author christophe
 */
public class LoginAction extends org.apache.struts.action.Action
{

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {



        // used to direct user to where he/she was going
        String action = request.getParameter("action");

        if (null == request.getUserPrincipal())
        {
            // someone got here without being authenticated... so force them to a login page
            return new ActionForward("/user/login.do", true);
        }

        String username =  request.getUserPrincipal().getName();




        // retrieve the user from the database
        User user = DBAccess.getInstance().getUserByUsername(username);

        request.getSession().setAttribute("user", user);


        if ("user".equals(user.getUserRole()))
        {
        
            ShoppingCart cart = DBAccess.getInstance().getShoppingCartByUserId(user.getUserID());
            if (null == cart)
            {
                Date now = new Date();
                // create a new cart for this user
                  cart = new ShoppingCart(
                        user,
                        request.getSession().getId(),
                        now,
                        now,
                        null);

                int cartId = DBAccess.getInstance().create(cart);
                cart.setShoppingCartId(cartId);

                cart = DBAccess.getInstance().retrieveByID(ShoppingCart.class, cartId);
            }
            request.getSession().setAttribute("cart", cart);
        
            return new ActionForward("/user/viewUser.do", true);
        }
        else if ("admin".equals(user.getUserRole()))
        {
            return new ActionForward("/welcome.do", true);
        }


         return new ActionForward("welcome", true);
    }
}
